let groupList = []
const store = require('../store/index').default

function initItem(item, isPush = true) {
  let index = groupList.findIndex(item1 => item1.num === item.num)
  if (index !== -1) {
    groupList.splice(index, 1)
  }
  if (!item.badge) {
    item.badge = 0
  }
  if (isPush) {
    groupList.push(item)
  } else {
    groupList.unshift(item)
  }

  setTimeout(() => {
    if (store.state.chat.groupNum === item.num) {
      store.commit('g/setIsRecMsg_fn', true)
    }
  }, 0);
}

function addList({ id, uid, num, name, nick, con, imgUrl, avatarUrl, isConfirm, isImg }) {
  let itm = groupList.find(item => item.num === num)
  if (itm && itm.messages) {
    if (num !== store.state.chat.groupNum) {
      itm.badge++
    }
    itm.messages.push({ id, name, uid, num, nick, con, imgUrl, avatarUrl, isConfirm, isImg })
    // console.log(itm);
    setTimeout(() => {
      if (store.state.chat.groupNum === num) {
        store.commit('g/setIsRecMsg_fn', true)
      }
    }, 0);
  }
}

function getList(num) {
  let itm = groupList.find(item => item.num === num)
  if (!itm || !itm.messages) {
    return []
  }
  return itm.messages
}

function deleteList(num) {
  let index = groupList.findIndex(item => item.num === num)
  if (index !== -1) {
    groupList.splice(index, 1)
  }
}

export default {
  initItem,
  groupList,
  addList,
  getList,
  deleteList
}